<template>
  <el-dialog :title="dataForm.propId ? $t('common.editBtn') : $t('common.addBtn')" v-model="visible" width="600">
    <el-form :model="dataForm" :rules="dataRules" label-width="100px" ref="dicDialogFormRef" v-loading="loading">
      <el-form-item :label="$t('ProdProp.rule')" prop="rule">
        <el-radio-group v-model="dataForm.rule">
          <el-radio border :key="index" :label="item.value" v-for="(item, index) in biz_prod_prop_rule">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('ProdProp.propName')" prop="propName">
        <el-input :placeholder="$t('ProdProp.inputPropNameTip')" :disabled="dataForm.propId !== ''" clearable
          v-model="dataForm.propName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
        <el-button @click="onSubmit" type="primary" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="systemDicDialog" setup>
import { useI18n } from 'vue-i18n';
import { addObj, getObj, putObj, validateDictType } from '/@/api/bizs/ProdProp';
import { useMessage } from '/@/hooks/message';


// 定义i18n
import { useDict } from '/@/hooks/dict';
const { t } = useI18n();

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { biz_prod_prop_rule } = useDict('biz_prod_prop_rule');

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const dicDialogFormRef = ref();

const dataForm = reactive({
  propId: '',
  propName: '',
  rule: 1,
  shopId: '',
});


import { rule } from '/@/utils/validate';
const dataRules = reactive({
  propName: [
    { required: true, message: t('ProdProp.inputPropNameTip'), trigger: 'blur' },
    { validator: rule.validatorNameCn, trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        validateDictType(rule, value, callback, dataForm.propId !== '');
      },
      trigger: 'blur',
    },
  ],
});

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true;
  dataForm.propId = '';
  dicDialogFormRef.value?.resetFields();

  if (id) {
    getObj(id).then((res) => {
      Object.assign(dataForm, res.data);
    });
  }

};

// 提交
const onSubmit = async () => {
  const valid = await dicDialogFormRef.value.validate().catch(() => { });
  if (!valid) return false;

  try {
    loading.value = true;
    const result = dataForm.propId ? await putObj(dataForm) : await addObj(dataForm);
    useMessage().success(t(dataForm.propId ? 'common.editSuccessText' : 'common.addSuccessText'));
    visible.value = false;
    emit('refresh', result.data);
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
